import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

questionnaire_project_api = Blueprint('questionnaire_project_api', __name__)
questionnaire_project_down_api = Blueprint('questionnaire_project_down_api', __name__)
questionnaire_schedule_api = Blueprint('questionnaire_schedule_api', __name__)
questionnaire_schedule_down_api = Blueprint('questionnaire_schedule_down_api', __name__)

USE_CMD_LOG = True


def questionnaire_log(module_name, host, info):
    if USE_CMD_LOG is False:
        return
    print(f'[Questionnaire] [{fomat_timestamp(int(time.time()))}] [Log] [{module_name}] host={host} - {info}',
          flush=True)


@questionnaire_project_api.route('/questionnaire_project', methods=['POST'])
def questionnaire_project():
    params = json.loads(request.data)

    # host = request.host
    print(request.headers, flush=True)
    if 'X-Forwarded-For' in request.headers:
        host = request.headers['X-Forwarded-For']
    else:
        host = request.host

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if _action == 'view':
        questionnaire_log('project', host, f'view project list')

        query = QuestionnaireProject.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "project": int(q.project),
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        questionnaire_log('project', host, f'view project detail project={_project}')
        query = QuestionnaireProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        questionnaire_log('project', host, f'update part project={_project}, part={_part}')

        if _part == 'basic':
            QuestionnaireProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })

        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        questionnaire_log('project', host, f'remark project={_project}')

        newRemark = params['remark']
        QuestionnaireProject.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':
        questionnaire_log('project', host, f'clone from={_project}')

        project_data = QuestionnaireProject.query.filter_by(project=_project).first()

        new_project_data = QuestionnaireProject(
            remark=project_data.remark,
            basic=project_data.basic
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            questionnaire_log('project', host, f'clone to={new_project_id}')
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        questionnaire_log('project', host, f'delete project={_project}')

        project_data = QuestionnaireProject.query.filter_by(project=_project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = QuestionnaireProject.query.filter_by(project=_project).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"

    return jsonify(result_data)


@questionnaire_project_down_api.route('/questionnaire_project_down/<int:is_push>', methods=['GET', 'POST'])
def questionnaire_project_down(is_push):
    host = request.host

    questionnaire_log('project_download', host, f'is_push={is_push}')

    questionnaire_project = {}

    query = QuestionnaireProject.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        questionnaire_project[str(project)] = {
            'ui': basic['ui'],
            'localization_doc': {
                'title': basic['doc_id']
            },
            'reward': RewardToTMysqlNew(basic['reward']),
            'url': basic['url']
        }
    if is_push == 0:
        response = DownLoad('questionnaire_project', questionnaire_project, 0)
    if is_push == 1:
        r1 = DownLoad('questionnaire_project', questionnaire_project, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response


@questionnaire_schedule_api.route('/questionnaire_schedule', methods=['POST'])
def questionnaire_schedule():
    params = json.loads(request.data)

    # host = request.host
    print(request.headers, flush=True)
    if 'X-Forwarded-For' in request.headers:
        host = request.headers['X-Forwarded-For']
    else:
        host = request.host

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if _action == 'view':
        questionnaire_log('schedule', host, f'view schedule list')

        query = QuestionnaireSchedule.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "project": int(q.project),
                'remark': q.remark,
                'basic': json.loads(q.basic)
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'delete':
        questionnaire_log('schedule', host, f'delete schedule={_project}')

        project_data = QuestionnaireSchedule.query.filter_by(project=_project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = QuestionnaireSchedule.query.filter_by(project=_project).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'getPidList':
        query = QuestionnaireProject.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "value": int(q.project),
                'label': f'{int(q.project)} - {q.remark}'
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'update':
        questionnaire_log('schedule', host, f'update schedule={_project}')

        data_list = params['dataList']
        query_list = QuestionnaireSchedule.query.all()
        for d in data_list:
            if d['project'] == -1:
                new_project_data = QuestionnaireSchedule(
                    remark=d['remark'],
                    basic=json.dumps(d['basic'])
                )
                db.session.add(new_project_data)
                db.session.commit()
            else:
                for query in query_list:
                    if query.project == d['project']:
                        query.remark = d['remark']
                        query.basic = json.dumps(d['basic'])
                        db.session.commit()
                        break

    return jsonify(result_data)

@questionnaire_schedule_down_api.route('/questionnaire_schedule_down/<int:is_push>', methods=['GET', 'POST'])
def questionnaire_schedule_down(is_push):
    host = request.host

    questionnaire_log('schedule_download', host, f'is_push={is_push}')

    questionnaire_schedule = {
        'schedule': []
    }

    query = QuestionnaireSchedule.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)

        if basic['end_time'] == '-1':
            end_time = -1
            close_time = -1
        else:
            end_time = fomat_date_str(basic['end_time'])
            close_time = fomat_date_str(basic['end_time'])

            current_time = int(time.time())
            if current_time > end_time:
                continue

        questionnaire_schedule['schedule'].append({
            'event_type': 123,
            'forecast_time': fomat_date_str(basic['begin_time']),
            'begin_time': fomat_date_str(basic['begin_time']),
            'end_time': end_time,
            'close_time': close_time,
            'event_id': f'123_{fomat_date_str(basic["begin_time"])}_{project}_{basic["pid"]}',
            'target': basic['target'],
            'pid': basic['pid']
        })

    if is_push == 0:
        response = DownLoad('questionnaire_schedule', questionnaire_schedule, 0)
    if is_push == 1:
        r1 = DownLoad('questionnaire_schedule', questionnaire_schedule, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response
